package com.spark.tags;

import java.util.Iterator;
import java.util.Map;

import com.spark.core.SparkBuilder;
import com.spark.core.SparkContext;
import com.spark.core.XMap;


public class ToolBar extends ViewComponent {
	
	private static final String DEFAULT_TEMPLATES = "toolBar.ftl";
	
	private static final String DEFAULT_CLASSNAME = "s_toolbar";
	public static final String PROPERTITY_ITEMS = "items";
	
	protected int getDefaultHeight(){
		return 28;
	}
	
	
	public String getTemplate() {
		return DEFAULT_TEMPLATES;
	}
	
	protected String getDefaultClass(XMap view, SparkContext context) {
		String className = super.getDefaultClass(view, context);
		StringBuilder sb = new StringBuilder();
		sb.append(className);
		if (!"".equals(className.trim()))
			sb.append(" ");
		sb.append(DEFAULT_CLASSNAME);
		return sb.toString();
	}
	
	@SuppressWarnings("unchecked")
	public void init(XMap view, SparkContext context) throws Exception {
		super.init(view, context);
		Integer height = (Integer)context.get(PROPERTITY_HEIGHT);
		StringBuilder sb = new StringBuilder();
		if(view != null && view.getChilds() != null) {
			Iterator it = view.getChildIterator();
			while(it.hasNext()){
				XMap editor = (XMap)it.next();
				String style = editor.getString(PROPERTITY_STYLE,"");
				if(DEFAULT_NAME_SPACE.equals(editor.getNamespaceURI()) && editor.getName().equalsIgnoreCase("button")){
//					editor.put(PROPERTITY_WIDTH, new Integer(1));
					style = "float:left;margin-right:1px;margin-top:2px;" + style;
				} else if(DEFAULT_NAME_SPACE.equals(editor.getNamespaceURI()) &&editor.getName().equalsIgnoreCase("separator")){
					style = "height:"+(height-4)+"px;margin-top:2px;float:left;margin-right:1px;" + style;	
				} else if(DEFAULT_NAME_SPACE.equals(editor.getNamespaceURI())){
					style = "float:left;margin-right:1px;margin-top:2px;" + style;
				} else{
					style = "float:left;margin-right:1px;line-height:"+(height)+"px;" + style;					
				}
				editor.put(PROPERTITY_STYLE, style);
				sb.append(SparkBuilder.build(editor, context));
			}
		}
		context.put(PROPERTITY_ITEMS, sb.toString());
	}
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<div class=\"").append(get(map,"className")).append("\" id=\"").append(get(map,"id")).append("\" style=\"height:").append(get(map,"height")).append("px;").append(get(map,"style")).append("\">\r");
		sb.append("	<div style=\"padding-left:4px;padding-right:4px;\">").append(get(map,"items")).append("</div>\r");
		sb.append("</div>\r");
		sb.append("<script>new Spark.ToolBar({id:'").append(get(map,"id")).append("',width:").append(get(map,"width")).append("});</script>\r");
		return sb.toString();
	}

}
